package com.heihei.web.controller;

import com.heihei.dto.User;
import com.heihei.exception.usernotexists.UserNotExistException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@RestController
@RequestMapping("/user")
public class UserController {

	@GetMapping("/me01")
	public Object getCurrentUser() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	@GetMapping("/me02")
	public Object getCurrentUser02(Authentication authentication) {
		return authentication;
	}

	@GetMapping("/me03")
	public Object getCurrentUser03(@AuthenticationPrincipal UserDetails user) {
		return user;
	}
	
	@GetMapping("/{id:\\d+}")
	public User getInfo(@ApiParam("用户id") @PathVariable String id) {

		System.out.println("进入getInfo服务");
		User user = new User();
		user.setUsername("tom");
		return user;
	}


	@PostMapping
	@ApiOperation(value = "创建用户")
	public User create(@Valid @RequestBody User user) {

		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday());

		user.setId("1");
		return user;
	}

	@DeleteMapping("/{id:\\d+}")
	public void delete(@PathVariable String id) {
		System.out.println(id);
	}


	@PutMapping("/{id:\\d+}")
	public User update(@Valid @RequestBody User user, BindingResult errors) {

		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday());

		user.setId("1");
		return user;
	}

	@GetMapping("/test-ex/{id:\\d+}")
	public String testException(@PathVariable String id) {
		throw new UserNotExistException(id);
	}
	


}
